import { ref, computed, type Ref } from 'vue'
import type { LogEntry, LogQuery, LogResponse } from '../../utils/wails-api'
import { wailsAPI } from '../../utils/wails-api'

export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'

export interface UseLoggerReturn {
  logs: Readonly<Ref<LogEntry[]>>
  total: Readonly<Ref<number>>
  loading: Readonly<Ref<boolean>>
  error: Readonly<Ref<string | null>>
  levelFilter: Ref<LogLevel | ''>
  moduleFilter: Ref<string>
  messageFilter: Ref<string>
  fetchLogs: (query?: Partial<LogQuery>) => Promise<void>
  clearLogs: () => Promise<void>
  refreshLogs: () => Promise<void>
}

export function useLogger(): UseLoggerReturn {
  const logs = ref<LogEntry[]>([])
  const total = ref(0)
  const loading = ref(false)
  const error = ref<string | null>(null)
  const levelFilter = ref<LogLevel | ''>('')
  const moduleFilter = ref('')
  const messageFilter = ref('')

  /**
   * 获取日志
   */
  const fetchLogs = async (query?: Partial<LogQuery>): Promise<void> => {
    loading.value = true
    error.value = null

    try {
      const queryParams: LogQuery = {
        limit: 100,
        ...query,
      }

      if (levelFilter.value) {
        queryParams.level = levelFilter.value
      }
      if (moduleFilter.value) {
        queryParams.module = moduleFilter.value
      }

      const response = await wailsAPI.getLogs(queryParams)
      let filteredLogs = response.logs.reverse() // 最新的在前

      // 前端过滤消息内容（如果有关键字）
      if (messageFilter.value.trim()) {
        const keyword = messageFilter.value.trim().toLowerCase()
        filteredLogs = filteredLogs.filter(log => 
          log.message.toLowerCase().includes(keyword)
        )
      }

      logs.value = filteredLogs
      total.value = filteredLogs.length
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取日志失败'
      console.error('获取日志失败:', err)
    } finally {
      loading.value = false
    }
  }

  /**
   * 清空日志
   */
  const clearLogs = async (): Promise<void> => {
    loading.value = true
    error.value = null

    try {
      await wailsAPI.clearLogs()
      logs.value = []
      total.value = 0
    } catch (err) {
      error.value = err instanceof Error ? err.message : '清空日志失败'
      console.error('清空日志失败:', err)
    } finally {
      loading.value = false
    }
  }

  /**
   * 刷新日志
   */
  const refreshLogs = async (): Promise<void> => {
    await fetchLogs()
  }

  return {
    logs: computed(() => logs.value),
    total: computed(() => total.value),
    loading: computed(() => loading.value),
    error: computed(() => error.value),
    levelFilter,
    moduleFilter,
    messageFilter,
    fetchLogs,
    clearLogs,
    refreshLogs,
  }
}

